const {
  ObjectID
} = require('bson');
var express = require('express');
const createError = require('http-errors');
var router = express.Router();
var db = require("../db");

/* GET users listing. */
router.get('/:id', async function (req, res, next) {
  let {
    id
  } = req.params;
  const {
    limit = 5,
      page = 0
  } = req.query

  try {
    id = new ObjectID(id)
  } catch {
    return next(createError(404, '该页面不存在！'))
  }

  // 根据ID查找 用户信息
  const user = await db.findOneUser({
    _id: id
  });

  if (!user) {
    return next = (createError(404, '该页面不存在！'))
  }

  // 根据用户信息 找到文章信息
  const posts = await db.findPost({
    authorId: id
  }, {
    limit: Number(limit),
    skip: limit * page
  })

  console.log(posts)
  res.render('user', {
    title: '用户',
    user,
    ...posts
  })
});

// 修改用户资料
router.get('/:id/edit', function (req, res, next) {
  res.render('user-edit', {
    title: '用户',
    user: {},
    posts: []
  })
});


module.exports = router;